package com.credithc.customers.base.utils;

import com.alibaba.fastjson.JSON;
import com.credithc.customers.base.codes.CustomerCodes;
import com.credithc.customers.base.constants.CustomerConstants;
import com.credithc.customers.base.exception.CustomerException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author zhukai
 * @date 2018/11/29 11:33
 */
@Slf4j
public class CustomerUtils {
    /**
     * 创建用户号
     *
     * @return string
     */
    public static String generatePreCustomerNo() {
        return CustomerConstants.PRE_CUSTOMER_PREFIX + generateRandomNumber();
    }

    /**
     * 创建个人客户号
     *
     * @return string
     */
    public static String generatePersonalCustomerNo() {
        return CustomerConstants.PERSONAL_CUSTOMER_PREFIX + generateRandomNumber();
    }

    /**
     * 创建公司客户号
     *
     * @return string
     */
    public static String generateCompanyCustomerNo() {
        return CustomerConstants.COMPANY_CUSTOMER_PREFIX + generateRandomNumber();
    }

    /**
     * 创建金融机构客户号
     *
     * @return string
     */
    public static String generateFinancialCustomerNo() {
        return CustomerConstants.FINANCIAL_CUSTOMER_PREFIX + generateRandomNumber();
    }

    /**
     * 生成随机数字符串
     *
     * @return 字符串
     */
    private static String generateRandomNumber() {
//        return RandomStringUtils.randomNumeric(6) + String.valueOf(System.currentTimeMillis());
        return RandomUtils.randomString(6) + String.valueOf(System.currentTimeMillis());

    }

    /**
     * @return Timestamp
     * @throws
     * @Title: getNowTimeStampTime
     * @Description: 获取当前时间（TimeStamp类型的）
     */
    public static Timestamp getNowTimeStampTime() {
        return new Timestamp(System.currentTimeMillis());
    }

    public static Timestamp stirng2Timestamp(String str) {
        if(StringUtils.isBlank(str)){
            return null;
        }
        Timestamp ts = null;
        try {
            ts = Timestamp.valueOf(str);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ts;
    }

    public static String timestamp2Stirng(Timestamp time) {
        if(time == null){
            return null;
        }
        String tsStr = null;
        DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            tsStr = sdf.format(time);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return tsStr;
    }

    public static String timestamp2DateString(Timestamp time) {
        if(time == null){
            return null;
        }
        String tsStr = null;
        DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            tsStr = sdf.format(time);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return tsStr;
    }

    /**
     * 正则表达式：验证手机号
     */
    public static final String REGEX_MOBILE = "^1[3,4,5,6,7,8,9][0-9]{9}$";

    /**
     * 正则表达式：验证ip
     */
    public static final String REGEX_IP = "^((\\d|[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5])\\.){3}(\\d|[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5]|[*])$";

    /**
     * 正则表达式：验证邮箱
     */
    public static final String REGEX_EMAIL = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
    /**
     * 正则表达式：验证身份证
     */
    public static final String REGEX_ID_CARD = "(^[1-9]\\d{5}(18|19|20)\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}[0-9Xx]$)|" +
            "(^[1-9]\\d{5}\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}$)";
    /**
     * 正则表达式：验证护照
     * 规则： 14/15开头 + 7位数字, G + 8位数字, P + 7位数字, S/D + 7或8位数字,等
     * 样本： 141234567, G12345678, P1234567
     */
    public static final String REGEX_ID_PASSPORT = "/^([a-zA-z]|[0-9]){5,17}$/";
    /**
     * 正则表达式：军官证
     * 规则： 军/兵/士/文/职/广/（其他中文） + "字第" + 4到8位字母或数字 + "号"
     * 样本： 军字第2001988号, 士字第P011816X号
     */
    public static final String REGEX_ID_COO = "/^[\\u4E00-\\u9FA5](字第)([0-9a-zA-Z]{4,8})(号?)$/";
    /**
     * 正则表达式：港澳居民来往内地通行证
     * 规则：H/M + 10位或6位数字
     * 样本： H1234567890
     */
    public static final String REGEX_ID_HKMAKAO = "/^[HMhm]{1}([0-9]{10}|[0-9]{8})$/";
    /**
     * 正则表达式：外国人居留许可证
     * 样本： USA110074110419
     */
    public static final String REGEX_ID_FOREIGN = "/^[a-zA-Z]{3}\\d{12}$/";

    // 密码长度6-18位且至少包含字母、数字或特殊符号中的至少2种
    public static final String REGEX_PASSWORD = "^(?![\\d]+$)(?![a-zA-Z]+$)(?![\\W_]+$)[\\da-zA-Z\\·\\~\\！\\@\\#\\￥\\%\\……\\&\\*\\（\\）\\——\\-\\+\\=\\【\\】\\{\\}\\、\\|\\；\\‘\\’\\：\\“\\”\\《\\》\\？\\，\\。\\、\\`\\~\\!\\#\\$\\%\\^\\&\\*\\(\\)\\_\\[\\]{\\}\\\\\\|\\;\\'\\'\\:\\,\\.\\/\\<\\>\\?\"\"]{6,18}$";

    public static boolean isPassword(String password) {
        return Pattern.matches(REGEX_PASSWORD, password);
    }

    public static boolean isMobil(String mobile) {
        return Pattern.matches(REGEX_MOBILE, mobile);
    }

    public static boolean isEmail(String email) {
        return Pattern.matches(REGEX_EMAIL, email);
    }

    public static boolean isIdCard(String idCard) {
        return Pattern.matches(REGEX_ID_CARD, idCard);
    }

    public static boolean isPassPort(String passport) {
        return Pattern.matches(REGEX_ID_PASSPORT, passport);
    }

    public static boolean isIdCoo(String idCoo) {
        return Pattern.matches(REGEX_ID_COO, idCoo);
    }

    public static boolean isHkmakao(String hkmakao) {
        return Pattern.matches(REGEX_ID_HKMAKAO, hkmakao);
    }

    public static boolean isIdForeign(String idForeign) {
        return Pattern.matches(REGEX_ID_FOREIGN, idForeign);
    }

    public static boolean isIp(String ip){
        return Pattern.matches(REGEX_IP, ip);
    }



    public static String reg = "(?:')|(?:--)|(/\\*(?:.|[\\n\\r])*?\\*/)|"
            + "(\\b(select|update|and|or|delete|insert|trancate|char|into|substr|ascii|declare|exec|count|master|into|drop|execute)\\b)";

    public static Pattern sqlPattern = Pattern.compile(reg, Pattern.CASE_INSENSITIVE);

    /***************************************************************************
     * 参数校验--防sql注入
     *
     * @param str
     */
    public static boolean  isValid(String str) {
        if (sqlPattern.matcher(str).find()) {
            return false;
        }
        return true;
    }

    public static void checkMobil(String mobile) {
        if (!isMobil(mobile)) {
            throw new CustomerException(CustomerCodes.PARAM_VALIDATE_ERROR, "手机号码格式错误");
        }
    }

    public static void checkEmail(String email) {
        if (!isEmail(email)) {
            throw new CustomerException(CustomerCodes.PARAM_VALIDATE_ERROR, "邮箱号码格式不正确");
        }
    }

    public static void checkIdCard(String idCard) {
        if (!isIdCard(idCard)) {
            throw new CustomerException(CustomerCodes.PARAM_VALIDATE_ERROR, "身份证号码格式不正确");
        }
    }

    public static void checkIdCoo(String idCoo) {
        if (!isIdCoo(idCoo)) {
            throw new CustomerException(CustomerCodes.PARAM_VALIDATE_ERROR, "军官证格式不正确");
        }
    }

    public static void checkPassPort(String passport) {
        if (!isPassPort(passport)) {
            throw new CustomerException(CustomerCodes.PARAM_VALIDATE_ERROR, "护照格式不正确");
        }
    }

    public static void checkHkmakao(String hkmakao) {
        if (!isHkmakao(hkmakao)) {
            throw new CustomerException(CustomerCodes.PARAM_VALIDATE_ERROR, "港澳台通行证格式不正确");
        }
    }

    public static void checkIdForeign(String idForeign) {
        if (!isIdForeign(idForeign)) {
            throw new CustomerException(CustomerCodes.PARAM_VALIDATE_ERROR, "外国人居留许可证格式不正确");
        }
    }

    public static void checkIdCardTypeAndNo(String idCardType, String idCardNo) {
        switch (idCardType) {
            case CustomerConstants.CERTIFICATE_TYPE_ID_CARD:
                checkIdCard(idCardNo);
                break;
//            case CustomerConstants.CERTIFICATE_TYPE_PASSPORT:
//                checkPassPort(idCardNo);
//                break;
//            case CustomerConstants.CERTIFICATE_TYPE_HMT:
//                checkHkmakao(idCardNo);
//                break;
//            case CustomerConstants.CERTIFICATE_TYPE_FOREIGNER:
//                checkIdForeign(idCardNo);
//                break;
//            case CustomerConstants.CERTIFICATE_TYPE_OFFICER:
//                checkIdCoo(idCardNo);
//                break;
            default:
                break;
        }
    }

    public static void checkContact(String contactType, String contactInfo) {
        checkContactType(contactType);
        checkContactInfo(contactInfo);
        switch (contactType) {
            case CustomerConstants.CONTACT_TYPE_MOBILE:
                checkMobil(contactInfo);
                break;
//            case CustomerConstants.CONTACT_TYPE_EMAIL:
//                checkEmail(contactInfo);
//                break;
            default:
                break;
        }
    }

    public static void checkIp(String ip) {
        if (!isIp(ip)) {
//            System.out.println("false");
            throw new CustomerException(CustomerCodes.PARAM_VALIDATE_ERROR, "ip格式不正确");
        }
    }

    public static void checkPassword(String password) {
        if (!isPassword(password)) {
            throw new CustomerException(CustomerCodes.PARAM_VALIDATE_ERROR, "新密码太简单，应为：6-18位字符，至少包括数字、字母、符号中的任意两种组合");
        }
    }

    public static void checkPassword1(String password) {
        if (!isPassword(password)) {
            throw new CustomerException(222, "密码错误,请重新尝试!");
        }
    }

    //基础参数校验

    /**
     * 校验请求流水号
     *
     * @param requestNo 请求流水号
     */
    public static void checkRequestNo(String requestNo) {
        if (StringUtils.isBlank(requestNo)) {
            throw new CustomerException(CustomerCodes.PARAM_VALIDATE_ERROR, "请求流水号不能为空");
        }
    }

    /**
     * 校验请求流水号
     *
     * @param customerType 客户类别
     */
    public static void checkCustomerType(String customerType) {
        if (StringUtils.isBlank(customerType)) {
            throw new CustomerException(CustomerCodes.PARAM_VALIDATE_ERROR, "客户类型不能为空");
        } else if (!CustomerConstants.IS_CUSTOMER_TYPE.contains(customerType)) {
            throw new CustomerException(CustomerCodes.PARAM_VALIDATE_ERROR, "客户类型不正确，只能是'1','2','3'");
        }
    }

    /**
     * 校验证件类型
     *
     * @param idCardType 证件类型
     */
    public static void checkIdCardType(String idCardType) {
        if (StringUtils.isBlank(idCardType)) {
            throw new CustomerException(CustomerCodes.PARAM_VALIDATE_ERROR, "证件类型不能为空");
        } else if (!CustomerConstants.ID_TYPE_LIST.contains(idCardType)) {
            throw new CustomerException(CustomerCodes.PARAM_VALIDATE_ERROR, "证件类型不正确，只能是'1','2','3','4','5'");
        }
    }

    /**
     * 校验证件号码
     *
     * @param idCardTypeNo 证件号码
     */
    public static void checkIdCardNo(String idCardTypeNo) {
        if (StringUtils.isBlank(idCardTypeNo)) {
            throw new CustomerException(CustomerCodes.PARAM_VALIDATE_ERROR, "证件号码不能为空");
        }
    }

    /**
     * 校验联系方式类型
     *
     * @param contactType 联系方式类型
     */
    public static void checkContactType(String contactType) {
        if (StringUtils.isBlank(contactType)) {
            throw new CustomerException(CustomerCodes.PARAM_VALIDATE_ERROR, "联系方式类型不能为空");
        } else {
            if (!CustomerConstants.CONTACT_TYPE_LIST.contains(contactType)) {
                throw new CustomerException(CustomerCodes.PARAM_VALIDATE_ERROR, "联系方式类型不正确，只能是'1','2','3','4'");
            }
        }
    }

    /**
     * 校验联系方式
     *
     * @param contactInfo 联系方式
     */
    public static void checkContactInfo(String contactInfo) {
        if (StringUtils.isBlank(contactInfo)) {
            throw new CustomerException(CustomerCodes.PARAM_VALIDATE_ERROR, "联系方式不能为空");
        }
    }

    /**
     * 校验客户号
     *
     * @param customerNo 客户号
     */
    public static void checkCustomerNo(String customerNo) {
        if (StringUtils.isBlank(customerNo)) {
            throw new CustomerException(CustomerCodes.PARAM_VALIDATE_ERROR, "客户号不能为空");
        }
    }

    /**
     * 校验客户姓名
     *
     * @param customerName 客户号
     */
    public static void checkCustomerName(String customerName) {
        if (StringUtils.isBlank(customerName)) {
            throw new CustomerException(CustomerCodes.PARAM_VALIDATE_ERROR, "客户姓名不能为空");
        }
    }

    /**
     * 校验三要素
     *
     * @param elementsVerified 三要素是否校验
     */
    public static void checkElementsVerified(Boolean elementsVerified) {
        if (elementsVerified == null) {
            throw new CustomerException(CustomerCodes.PARAM_VALIDATE_ERROR, "三要素校验状态不能为空");
        }
    }

    /**
     * 校验法人姓名
     *
     * @param legalName 法人姓名
     */
    public static void checkLegalName(String legalName) {
        if (StringUtils.isBlank(legalName)) {
            throw new CustomerException(CustomerCodes.PARAM_VALIDATE_ERROR, "法人姓名不能为空");
        }
    }


    public static <T> List copyList(List<T> list) {
        if (CollectionUtils.isEmpty(list)) {
            return new ArrayList();
        }
        return JSON.parseArray(JSON.toJSONString(list), list.get(0).getClass());
    }

    public static Map<String, Object> copyMap(Map map) {
        return JSON.parseObject(JSON.toJSONString(map));
    }

    private static final String REG_ASSOCIATED_PRE_NO = "^\\w+(,\\w+)*$";

    public static void verifyAssociatedPreNo(String associatedPreNo){
        if(StringUtils.isNotBlank(associatedPreNo)){
            if(!Pattern.matches(REG_ASSOCIATED_PRE_NO,associatedPreNo)){
                throw new CustomerException(CustomerCodes.PARAM_VALIDATE_ERROR, "关联用户号格式不正确");
            }
        }
    }

    public static Timestamp dateStr2Timestamp(String dateStr){
        if(StringUtils.isNotBlank(dateStr)){
            String[] s = dateStr.split(" ");


            String str = s[0]+" 00:00:00";

            Timestamp timestamp = Timestamp.valueOf(str);

            try{
                str =s[0]+" "+s[1];
                timestamp = Timestamp.valueOf(str);
            }catch (Exception e){
            }
            return timestamp;
        }else {
            return null;
        }
    }

    public static void checkPreCustomerNo(String preCustomerNo) {
        if (StringUtils.isBlank(preCustomerNo)) {
            throw new CustomerException(CustomerCodes.PARAM_VALIDATE_ERROR, "用户号不能为空");
        }
    }

    /**
     * 校验手机号码
     *
     * @param phone 手机号码
     */
    public static void checkPhone(String phone) {
        if (StringUtils.isBlank(phone)) {
            throw new CustomerException(CustomerCodes.PARAM_VALIDATE_ERROR, "手机号码不能为空");
        }
        checkMobil(phone);
    }

    public static void checkCode(String code) {
        if (StringUtils.isBlank(code)) {
            throw new CustomerException(CustomerCodes.PARAM_VALIDATE_ERROR, "code不能为空");
        }
    }
    public static void checkMainSystemId(String mainSystemId) {
        if (StringUtils.isBlank(mainSystemId)) {
            throw new CustomerException(CustomerCodes.PARAM_VALIDATE_ERROR, "mainSystemId不能为空");
        }
        if(!CustomerConstants.HSH.equals(mainSystemId)){
            throw new CustomerException(CustomerCodes.PARAM_VALIDATE_ERROR, "mainSystemId当前仅支持恒生活系统");
        }
    }
    public static void checkTimestamp(String timestamp) {
        if (StringUtils.isBlank(timestamp)) {
            throw new CustomerException(CustomerCodes.PARAM_VALIDATE_ERROR, "timestamp不能为空");
        }
    }
    public static void checkSubSystemId(String subSystemId) {
        if (StringUtils.isBlank(subSystemId)) {
            throw new CustomerException(CustomerCodes.PARAM_VALIDATE_ERROR, "subSystemId不能为空");
        }
    }
    public static void checkSystemSign(String systemSign) {
        if (StringUtils.isBlank(systemSign)) {
            throw new CustomerException(CustomerCodes.PARAM_VALIDATE_ERROR, "systemSign不能为空");
        }
    }
    public static void checkSubSystemSign(String subSystemSign) {
        if (StringUtils.isBlank(subSystemSign)) {
            throw new CustomerException(CustomerCodes.PARAM_VALIDATE_ERROR, "subSystemSign不能为空");
        }
    }

    public static void checkVerifyCode(String verifyCode) {
        if (StringUtils.isBlank(verifyCode)) {
            throw new CustomerException(CustomerCodes.PARAM_VALIDATE_ERROR, "verifyCode不能为空");
        }
    }

    public static void checkChannel(String channel) {
        if (StringUtils.isBlank(channel)) {
            throw new CustomerException(CustomerCodes.PARAM_VALIDATE_ERROR, "channel");
        }
    }

    public static void checkExt1(String ext1) {
        if (StringUtils.isBlank(ext1)) {
            throw new CustomerException(CustomerCodes.PARAM_VALIDATE_ERROR, "ext1不能为空");
        }
    }
    public static void checkExt2(String ext2) {
        if (StringUtils.isBlank(ext2)) {
            throw new CustomerException(CustomerCodes.PARAM_VALIDATE_ERROR, "ext2不能为空");
        }
    }
    public static void checkExt3(String ext3) {
        if (StringUtils.isBlank(ext3)) {
            throw new CustomerException(CustomerCodes.PARAM_VALIDATE_ERROR, "ext3不能为空");
        }
    }

    public static String getIp2(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if(StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)){
            //多次反向代理后会有多个ip值，第一个ip才是真实ip
            log.info("==========================系统请求X-Forwarded-For:"+ip);
            int index = ip.indexOf(",");
            if(index != -1){
                return ip.substring(0,index);
             }else{
                return ip;
             }
        }
        ip = request.getHeader("X-Real-IP");
        if(StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)){
            log.info("==========================系统请求X-Real-IP:"+ip);
            return ip;
        }
        log.info("==========================系统请求RemoteIp:"+ip);
            return request.getRemoteAddr();
        }


    public static void checkMoney(String money) {
        if (StringUtils.isBlank(money)) {
            throw new CustomerException(CustomerCodes.PARAM_VALIDATE_ERROR, "money不能为空");
        }
        try {
            if (!(Double.parseDouble(money) > 0)) {
                throw new CustomerException(CustomerCodes.PARAM_VALIDATE_ERROR, "money必须大于0");
            }
        } catch (Exception e) {
            throw new CustomerException(CustomerCodes.PARAM_VALIDATE_ERROR, "money必须为数字");
        }
    }

    public static String getPastDate(int past, String dateStr) {
        Calendar calendar = Calendar.getInstance();
        if (StringUtils.isNotBlank(dateStr)) {
            String[] date = dateStr.split("-");
            calendar.set(Integer.valueOf(date[0]), Integer.valueOf(date[1]) - 1, Integer.valueOf(date[2]));
        }
        calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) - past);
        Date today = calendar.getTime();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String result = format.format(today);
        return result;
    }

    /**
     * 判断传入日期是否小于当前日期
     * @return
     * @return
     */
    public static boolean isPastDate(String str){

        boolean flag = false;
        Date nowDate = new Date();
        Date pastDate = null;
        //格式化日期
        SimpleDateFormat sdf =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //在日期字符串非空时执行
        if (str != null && !"".equals(str)) {
            try {
                //将字符串转为日期格式，如果此处字符串为非合法日期就会抛出异常。
                pastDate = sdf.parse(str);
                //调用Date里面的before方法来做判断
                flag = pastDate.before(nowDate);
                if (flag) {
                    log.info("该日期早于今日");
                    flag=true;
                }else {
                    log.info("该日期晚于今日");
                    flag=false;
                }
            } catch (ParseException e) {

            }
        }else {
            log.info("日期参数不可为空");
        }
        return flag;
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        CustomerUtils p=new CustomerUtils();
        String ii="127.0.0.1";
        String ii2="127.0.0.";
        String ii3="127.0.0.1000";
        String ii4="256.0.0.1";
        String ii5="127.0.0.gg";
        String ii6="127.h.0.1";
        String ii7="127.555.0.1";
        String ii8="127.00.0.1";
        String ii9="127.0.04.1";
        String ii10="127.100.#.1";
        String ii11="127.*.0.1";
        String ii12="127.0.0.000";
        String ii13="192.168.3.12";
        String ii14="192.168.3.255";
        String ii15="192.168.3.256";
        System.out.println("ip校验正则 的测试结果：");
        checkIp(ii);
        checkIp(ii2);
        checkIp(ii3);
        checkIp(ii4);
        checkIp(ii5);
        checkIp(ii6);
        checkIp(ii7);
        checkIp(ii8);
        checkIp(ii9);
        checkIp(ii10);
        checkIp(ii11);
        checkIp(ii12);
        checkIp(ii13);
        checkIp(ii14);
        checkIp(ii15);

//        p.isMatches(ii);
//        p.isMatches(ii2);
//        p.isMatches(ii3);
//        p.isMatches(ii4);
//        p.isMatches(ii5);
//        p.isMatches(ii6);
//        p.isMatches(ii7);
//        p.isMatches(ii8);
//        p.isMatches(ii9);
//        p.isMatches(ii10);
//        p.isMatches(ii11);
//        p.isMatches(ii12);
//        p.isMatches(ii13);
//        p.isMatches(ii14);
    }
    public boolean isMatches(String ip){
        boolean flag=false;
        try{
//  String regex="[0-9]+[.][0-9]+[.][0-9]+[.][0-9]+";
//            String regex="^((\\d|[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5]|[*])\\.){3}(\\d|[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5]|[*])$";
            String regex="^((\\d|[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5])\\.){3}(\\d|[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5]|[*])$";            //正确的是
//String regex="^((\\d|[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5])\\.){3}(\\d|[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5]|[*])$";
//  String regex="\\b((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\.((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\.((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\.((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\b";
            Pattern p=Pattern.compile(regex);
            Matcher m=p.matcher(ip);
            if(m.find()){
                System.out.println("successss");
                return true;
            }else{
                System.out.println("falsss");
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        return flag;
    }
}

